<template>
  <ErpLayout>
    <div class="modern-page profile-detail">
      <!-- 页面头部 -->
      <div class="profile-header modern-card__header">
        <t-breadcrumb class="modern-breadcrumb">
          <t-breadcrumb-item to="/dashboard">首页</t-breadcrumb-item>
          <t-breadcrumb-item>个人信息</t-breadcrumb-item>
        </t-breadcrumb>
        <h1 class="page-title modern-text-gradient">个人信息</h1>
        <p class="page-description">管理您的个人资料和账户设置</p>
      </div>

    <div class="profile-content">
      <!-- 左侧头像区域 -->
      <div class="profile-avatar-section">
        <t-card title="头像设置" :bordered="false" class="modern-card modern-card-interactive">
          <div class="avatar-container">
            <t-avatar 
              size="120px" 
              :image="userInfo.avatar"
              class="user-avatar modern-shadow-lg"
            >
              {{ (userInfo.nickname || userInfo.username)?.charAt(0)?.toUpperCase() }}
            </t-avatar>
            <div class="avatar-actions">
              <t-upload
                v-model="avatarFiles"
                theme="file-input"
                accept="image/*"
                :size-limit="{ size: 2, unit: 'MB' }"
                :before-upload="handleBeforeAvatarUpload"
                :on-success="handleAvatarUploadSuccess"
                :on-fail="handleAvatarUploadFail"
              >
                <t-button theme="primary" variant="outline" size="medium" class="modern-btn-enhance">
                  <template #icon><component :is="'CloudUploadIcon'" /></template>
                  更换头像
                </t-button>
              </t-upload>
              <p class="avatar-tip">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
            </div>
          </div>
        </t-card>
      </div>

      <!-- 右侧信息区域 -->
      <div class="profile-info-section">
        <!-- 基本信息 -->
        <t-card title="基本信息" :bordered="false" class="modern-card info-card">
          <t-form
            ref="basicFormRef"
            :data="basicForm"
            :rules="basicFormRules"
            label-align="left"
            label-width="100px"
            :colon="true"
            class="modern-form"
          >
            <!-- 动态渲染表单字段 -->
            <template v-for="(row, rowIndex) in formFields" :key="rowIndex">
            <t-row :gutter="24">
                <t-col 
                  v-for="field in row" 
                  :key="field.name" 
                  :span="field.span || 12"
                >
                  <t-form-item :label="field.label" :name="field.name">
                    <!-- 输入框 -->
                  <t-input 
                      v-if="field.type === 'input'"
                      v-model="basicForm[field.name]" 
                      :placeholder="field.placeholder"
                      :disabled="field.disabled || !isEditing"
                      class="modern-input"
                  />
                    <!-- 单选组 -->
                    <t-radio-group 
                      v-else-if="field.type === 'radio'"
                      v-model="basicForm[field.name]" 
                    :disabled="!isEditing"
                    >
                      <t-radio 
                        v-for="option in field.options" 
                        :key="option.value" 
                        :value="option.value"
                      >
                        {{ option.label }}
                      </t-radio>
                  </t-radio-group>
                    <!-- 日期选择器 -->
                  <t-date-picker 
                      v-else-if="field.type === 'date'"
                      v-model="basicForm[field.name]" 
                      :placeholder="field.placeholder"
                    :disabled="!isEditing"
                      :format="field.format || 'YYYY-MM-DD'"
                      class="modern-date-picker"
                  />
                    <!-- 文本域 -->
                  <t-textarea 
                      v-else-if="field.type === 'textarea'"
                      v-model="basicForm[field.name]" 
                      :placeholder="field.placeholder"
                    :disabled="!isEditing"
                      :maxlength="field.maxlength || 200"
                      :autosize="field.autosize || { minRows: 3, maxRows: 5 }"
                  />
                </t-form-item>
              </t-col>
            </t-row>
            </template>
          </t-form>

          <div class="form-actions">
            <t-space>
              <t-button 
                v-if="!isEditing" 
                theme="primary" 
                @click="handleEdit"
              >
                <template #icon><EditIcon /></template>
                编辑信息
              </t-button>
              <template v-else>
                <t-button 
                  theme="primary" 
                  :loading="saveLoading"
                  @click="handleSave"
                >
                  <template #icon><CheckIcon /></template>
                  保存修改
                </t-button>
                <t-button 
                  theme="default" 
                  @click="handleCancel"
                >
                  <template #icon><CloseIcon /></template>
                  取消
                </t-button>
              </template>
            </t-space>
          </div>
        </t-card>

        <!-- 账户信息 -->
        <t-card title="账户信息" :bordered="true" class="info-card">
          <t-descriptions :column="2" size="medium">
            <t-descriptions-item label="用户ID">
              {{ userInfo.id || '--' }}
            </t-descriptions-item>
            <t-descriptions-item label="角色">
              <t-tag theme="primary" variant="light">
                {{ userInfo.role || '管理员' }}
              </t-tag>
            </t-descriptions-item>
            <t-descriptions-item label="注册时间">
              {{ formatDate(userInfo.createdAt) || '--' }}
            </t-descriptions-item>
            <t-descriptions-item label="最后登录">
              {{ formatDate(userInfo.lastLoginAt) || '--' }}
            </t-descriptions-item>
            <t-descriptions-item label="账户状态">
              <t-tag :theme="userInfo.status === 'active' ? 'success' : 'warning'">
                {{ userInfo.status === 'active' ? '正常' : '禁用' }}
              </t-tag>
            </t-descriptions-item>
            <t-descriptions-item label="登录次数">
              {{ userInfo.loginCount || 0 }} 次
            </t-descriptions-item>
          </t-descriptions>
        </t-card>

        <!-- 安全设置 -->
        <t-card title="安全设置" :bordered="true" class="info-card">
          <div class="security-items">
            <div class="security-item">
              <div class="security-info">
                <h4>登录密码</h4>
                <p class="security-desc">定期更换密码可以提高账户安全性</p>
              </div>
              <div class="security-action">
                <t-button theme="primary" variant="outline" @click="handleChangePassword">
                  <template #icon><LockOnIcon /></template>
                  修改密码
                </t-button>
              </div>
            </div>
            
            <t-divider />
            
            <div class="security-item">
              <div class="security-info">
                <h4>两步验证</h4>
                <p class="security-desc">开启两步验证可以进一步保护您的账户安全</p>
              </div>
              <div class="security-action">
                <t-switch 
                  v-model="twoFactorEnabled" 
                  @change="handleTwoFactorChange"
                />
              </div>
            </div>
          </div>
        </t-card>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <t-dialog
      v-model:visible="passwordDialogVisible"
      header="修改密码"
      width="480px"
      :confirm-btn="{ content: '确认修改', loading: passwordLoading }"
      @confirm="handlePasswordSubmit"
      @cancel="handlePasswordCancel"
    >
      <t-form
        ref="passwordFormRef"
        :data="passwordForm"
        :rules="passwordFormRules"
        label-align="left"
        label-width="100px"
        :colon="true"
      >
        <t-form-item label="当前密码" name="currentPassword">
          <t-input 
            v-model="passwordForm.currentPassword" 
            type="password"
            placeholder="请输入当前密码"
          />
        </t-form-item>
        <t-form-item label="新密码" name="newPassword">
          <t-input 
            v-model="passwordForm.newPassword" 
            type="password"
            placeholder="请输入新密码"
          />
        </t-form-item>
        <t-form-item label="确认密码" name="confirmPassword">
          <t-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            placeholder="请再次输入新密码"
          />
        </t-form-item>
      </t-form>
    </t-dialog>
    </div>
  </ErpLayout>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { MessagePlugin } from 'tdesign-vue-next'
import ErpLayout from '@/layouts/ErpLayout.vue'

const userStore = useUserStore()

// 响应式数据
const isEditing = ref(false)
const saveLoading = ref(false)
const passwordDialogVisible = ref(false)
const passwordLoading = ref(false)
const twoFactorEnabled = ref(false)
const avatarFiles = ref([])

// 表单引用
const basicFormRef = ref(null)
const passwordFormRef = ref(null)

// 用户信息
const userInfo = computed(() => userStore.userInfo || {})

// 基本信息表单
const basicForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 'male',
  birthday: '',
  bio: ''
})

// 表单字段配置
const formFields = ref([
  // 第一行
  [
    {
      name: 'username',
      label: '用户名',
      type: 'input',
      placeholder: '请输入用户名',
      disabled: true,
      span: 12
    },
    {
      name: 'nickname',
      label: '昵称',
      type: 'input',
      placeholder: '请输入昵称',
      span: 12
    }
  ],
  // 第二行
  [
    {
      name: 'email',
      label: '邮箱',
      type: 'input',
      placeholder: '请输入邮箱',
      span: 12
    },
    {
      name: 'phone',
      label: '手机号',
      type: 'input',
      placeholder: '请输入手机号',
      span: 12
    }
  ],
  // 第三行
  [
    {
      name: 'gender',
      label: '性别',
      type: 'radio',
      options: [
        { value: 'male', label: '男' },
        { value: 'female', label: '女' },
        { value: 'other', label: '其他' }
      ],
      span: 12
    },
    {
      name: 'birthday',
      label: '生日',
      type: 'date',
      placeholder: '请选择生日',
      format: 'YYYY-MM-DD',
      span: 12
    }
  ],
  // 第四行
  [
    {
      name: 'bio',
      label: '个人简介',
      type: 'textarea',
      placeholder: '请输入个人简介',
      maxlength: 200,
      autosize: { minRows: 3, maxRows: 5 },
      span: 24
    }
  ]
])

// 基本信息表单验证规则
const basicFormRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度应在2-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordFormRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, message: '密码应包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (val) => val === passwordForm.newPassword, 
      message: '两次输入的密码不一致', 
      trigger: 'blur' 
    }
  ]
}

// 初始化表单数据
const initFormData = () => {
  basicForm.username = userInfo.value.username || ''
  basicForm.nickname = userInfo.value.nickname || ''
  basicForm.email = userInfo.value.email || ''
  basicForm.phone = userInfo.value.phone || ''
  basicForm.gender = userInfo.value.gender || 'male'
  basicForm.birthday = userInfo.value.birthday || ''
  basicForm.bio = userInfo.value.bio || ''
}

// 编辑信息
const handleEdit = () => {
  isEditing.value = true
}

// 保存修改
const handleSave = async () => {
  try {
    const valid = await basicFormRef.value?.validate()
    if (!valid) return

    saveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该调用实际的API更新用户信息
    // await userStore.updateUserInfo(basicForm)
    
    MessagePlugin.success('个人信息更新成功')
    isEditing.value = false
  } catch (error) {
    MessagePlugin.error('保存失败，请重试')
  } finally {
    saveLoading.value = false
  }
}

// 取消编辑
const handleCancel = () => {
  isEditing.value = false
  initFormData() // 重置表单数据
}

// 修改密码
const handleChangePassword = () => {
  passwordDialogVisible.value = true
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  try {
    const valid = await passwordFormRef.value?.validate()
    if (!valid) return

    passwordLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该调用实际的API修改密码
    // await userStore.changePassword(passwordForm)
    
    MessagePlugin.success('密码修改成功')
    passwordDialogVisible.value = false
    
    // 清空表单
    Object.keys(passwordForm).forEach(key => {
      passwordForm[key] = ''
    })
  } catch (error) {
    MessagePlugin.error('密码修改失败，请重试')
  } finally {
    passwordLoading.value = false
  }
}

// 取消密码修改
const handlePasswordCancel = () => {
  passwordDialogVisible.value = false
  Object.keys(passwordForm).forEach(key => {
    passwordForm[key] = ''
  })
}

// 两步验证切换
const handleTwoFactorChange = (value) => {
  if (value) {
    MessagePlugin.info('两步验证功能开发中...')
  } else {
    MessagePlugin.info('已关闭两步验证')
  }
}

// 头像上传前处理
const handleBeforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    MessagePlugin.error('只能上传图片文件')
    return false
  }
  if (!isLt2M) {
    MessagePlugin.error('图片大小不能超过 2MB')
    return false
  }
  return true
}

// 头像上传成功
const handleAvatarUploadSuccess = (context) => {
  MessagePlugin.success('头像上传成功')
  // 这里应该更新用户头像
  // userStore.updateAvatar(context.response.url)
}

// 头像上传失败
const handleAvatarUploadFail = () => {
  MessagePlugin.error('头像上传失败，请重试')
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '--'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时初始化数据
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.profile-detail {
  padding: 24px;
  min-height: 100%;
}

.profile-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 16px 0 8px 0;
}

.page-description {
  color: #6b7280;
  margin: 0 0 24px 0;
}

.profile-content {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 24px;
}

.profile-avatar-section {
  display: flex;
  flex-direction: column;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px;
}

.user-avatar {
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.avatar-tip {
  font-size: 12px;
  color: #6b7280;
  text-align: center;
  margin: 0;
}

.profile-info-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.info-card {
  background: white;
  border-radius: var(--modern-radius-lg);
}

.form-actions {
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

/* 现代化表单样式 */
.modern-form {
  :deep(.t-form-item) {
    margin-bottom: 1.5rem;
  }
  
  :deep(.t-form-item__label) {
    font-weight: 600;
    color: var(--modern-text-secondary);
    margin-bottom: 0.5rem;
  }
  
  :deep(.modern-input),
  :deep(.modern-date-picker .t-input) {
    border-radius: var(--modern-radius-md);
    transition: var(--modern-transition-normal);
    
    &:hover {
      box-shadow: var(--modern-shadow-sm);
    }
    
    &.t-is-focused {
      box-shadow: var(--modern-shadow-md);
      border-color: rgba(99, 102, 241, 0.5);
    }
  }
  
  :deep(.t-textarea) {
    border-radius: var(--modern-radius-md);
    transition: var(--modern-transition-normal);
    
    &:hover {
      box-shadow: var(--modern-shadow-sm);
    }
    
    &.t-is-focused {
      box-shadow: var(--modern-shadow-md);
      border-color: rgba(99, 102, 241, 0.5);
    }
  }
}

/* 头像容器样式 */
.avatar-container {
  text-align: center;
  padding: 1.5rem;
}

.user-avatar {
  border: 4px solid white;
  box-shadow: var(--modern-shadow-xl);
  margin-bottom: 1rem;
}

.avatar-actions {
  margin-top: 1rem;
}

.avatar-tip {
  font-size: 0.75rem;
  color: var(--modern-text-muted);
  margin-top: 0.5rem;
  margin-bottom: 0;
}

/* 现代化面包屑 */
.modern-breadcrumb {
  margin-bottom: 1rem;
  
  :deep(.t-breadcrumb-item) {
    color: var(--modern-text-muted);
    
    &:last-child {
      color: var(--modern-text-secondary);
      font-weight: 500;
    }
  }
}

/* 页面标题 */
.page-title {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  letter-spacing: -0.025em;
}

.page-description {
  color: var(--modern-text-muted);
  margin-bottom: 2rem;
}

.security-items {
  padding: 8px 0;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.security-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
}

.security-desc {
  margin: 0;
  font-size: 14px;
  color: #6b7280;
}

.security-action {
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-content {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .profile-detail {
    padding: 16px;
  }
}
</style>
